#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKeyboard.h>
#import <LockInfo/Plugin.h>

#import "FWApplication.h"
#import "FWPlugin.h"
#import "FWCommon.h"

#import "FWInputView.h"


@implementation FWInputView

@synthesize navBar, application, text, textLabel, done, hasFired, lightBackground;

static NSTimeInterval const kViewAnimationDuration = 0.75;
static NSTimeInterval const kKeyboardAnimationDuration = 0.3;


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

- (id)initWithFrame:(CGRect)rect caption:(NSString*)caption label:(NSString*)labl prompt:(NSString*)prompt application:(FWApplication*)appl preferences:(FWPreferences*)prefs
{
    if ((self = [super initWithFrame:rect])) {
        self.application = appl;
        self.hasFired = NO;
        
        NSBundle* bundle = [NSBundle bundleForClass:[self class]];
        
        UIBarButtonItem* doneBtn = [[[UIBarButtonItem alloc]
                                     initWithTitle:localize(bundle, @"Detail/Button/Done")
                                     style:UIBarButtonItemStyleBordered 
                                     target:self
                                     action:@selector(doneClicked)] autorelease];

        doneBtn.enabled = NO;
        
        UIBarButtonItem* cancelBtn = [[[UIBarButtonItem alloc]
                                       initWithTitle:localize(bundle, @"Detail/Button/Cancel")
                                       style:UIBarButtonItemStyleBordered 
                                       target:self
                                       action:@selector(cancelClicked)] autorelease];
        
        const CGFloat toolbarHeight = 44;
        CGRect navBarFrame = CGRectMake(0, 0, rect.size.width, toolbarHeight);
        CGRect windowFrame = CGRectMake(0, toolbarHeight, rect.size.width, rect.size.height - toolbarHeight);
        
        UINavigationBar* nav = [[[UINavigationBar alloc] initWithFrame:navBarFrame] autorelease];
        nav.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        nav.barStyle = UIBarStyleBlackOpaque;
        self.navBar = nav;
        
        UINavigationItem* navItem = [[[UINavigationItem alloc] initWithTitle:localize(bundle, caption)] autorelease];
        navItem.leftBarButtonItem = cancelBtn;
        navItem.rightBarButtonItem = doneBtn;
        
        [nav setItems:[NSArray arrayWithObjects:navItem, nil] animated:NO];
        [self addSubview:nav];
        
        UILabel* label = [[[UILabel alloc] init] autorelease];
        label.backgroundColor = [UIColor clearColor];
        label.clipsToBounds = NO;
        label.shadowOffset = CGSizeMake(1.0, 1.0);
        label.font = [UIFont boldSystemFontOfSize:[UIFont labelFontSize]];
        label.text = localize(bundle, labl);
        [label sizeToFit];
        self.textLabel = label;
 
        UITextField* textView = [[[UITextField alloc] initWithFrame:CGRectZero] autorelease];
        textView.delegate = self;
        textView.enablesReturnKeyAutomatically = YES;
        textView.placeholder = localize(bundle, prompt);
        textView.clearButtonMode = UITextFieldViewModeWhileEditing;
        textView.borderStyle = UITextBorderStyleRoundedRect;
        textView.font = [UIFont boldSystemFontOfSize:[UIFont labelFontSize]];
        textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        self.text = textView;
        
        if (FWIsDeviceAnIPad()) {
            label.frame = CGRectMake(windowFrame.origin.x + 80, windowFrame.origin.y + 15, label.frame.size.width, label.frame.size.height);
            textView.frame = CGRectMake(windowFrame.origin.x + 100, label.frame.origin.y + label.frame.size.height + 5, windowFrame.size.width - 180, textView.font.leading + 4);
        }
        else {
            label.frame = CGRectMake(windowFrame.origin.x + 15, windowFrame.origin.y + 15, label.frame.size.width, label.frame.size.height);
            textView.frame = CGRectMake(windowFrame.origin.x + 20, label.frame.origin.y + label.frame.size.height + 5, windowFrame.size.width - 35, textView.font.leading + 4);
        }
        
        [self addSubview:label];
        [self addSubview:textView];

        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.autoresizesSubviews = YES;
        self.opaque = YES;
        
        if ([[UIColor class] respondsToSelector:@selector(underPageBackgroundColor)]) {
            self.backgroundColor = [UIColor underPageBackgroundColor];
            label.textColor = [UIColor darkGrayColor];
            label.shadowColor = [UIColor whiteColor];
            lightBackground = YES;
        }
        else {
            self.backgroundColor = [UIColor viewFlipsideBackgroundColor];
            label.textColor = [UIColor whiteColor];
            label.shadowColor = [UIColor clearColor];
            lightBackground = NO;
        }
        
        self.done = doneBtn;
    }
    
    return self;
}

- (void)dealloc
{
    [application release];
    [navBar release];
    [text release];
    [textLabel release];
    [done release];
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Layout management - try to look reasonable on both iPhone and iPad

- (void)layoutSubviews
{
    CGSize size = FWGetCurrentScreenSize();
    
    CGFloat origin = self.navBar.frame.origin.y + self.navBar.frame.size.height;
    
    CGRect textFrame = self.text.frame;
    CGRect textLabelFrame = self.textLabel.frame;
    
    if (size.height > size.width || FWIsDeviceAnIPad()) {
        textLabelFrame.origin.y = origin + (FWIsDeviceAnIPad() ? 100 : 20);
        textFrame.origin.y = textLabelFrame.origin.y + textLabelFrame.size.height + 10;
    }
    else {
        // Not much room on a hiorizonal iPhone so squeeze things together!
        textLabelFrame.origin.y = origin;
        textFrame.origin.y = textLabelFrame.origin.y + textLabelFrame.size.height + 2;
    }
    
    self.text.frame = textFrame;
    self.textLabel.frame = textLabelFrame;
    
    [super layoutSubviews];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Keyboard management - one big hack on a lockscreen!

- (void)showKeyboardAfterDelay
{
    if (visible)
        [self showKeyboard:YES];
}

- (void)willMoveToWindow:(id)window
{
    if (!window) {
        XLog(@"LI:PITask: willMoveToWindow NIL called on PITaskCreate - deactivate keyboard");
        visible = NO;
        [self hideKeyboard:YES];
    }
}

- (void)didMoveToWindow
{
    if (self.window) {
        XLog(@"LI:PITask: didMoveToWindow not NIL called on PITaskCreate - activate keyboard");

        visible = YES;
        [self performSelector:@selector(showKeyboardAfterDelay) withObject:nil afterDelay:kViewAnimationDuration];
    }
}

- (void)showKeyboard:(BOOL)animation
{
    if (!showingKeyboard) {
        [text becomeFirstResponder];
#ifndef DEVELOPMENT_MODE
        [self.application.fwPlugin.liPlugin showKeyboard:text];
#endif

        showingKeyboard = YES;
    }
}

- (void)hideKeyboard:(BOOL)animation
{
    if (showingKeyboard) {
        [text resignFirstResponder];
#ifndef DEVELOPMENT_MODE
        [self.application.fwPlugin.liPlugin dismissKeyboard];
#endif
        
        showingKeyboard = NO;
    }
}


// ******************************************************************************************
#pragma mark -
#pragma mark Command button callbacks

- (void)cancelClickedAfterDelay
{
    if (visible) {
        self.hasFired = YES;
        [self.application.fwPlugin.liPlugin dismissPreview];
    }
}

- (void)cancelClicked
{
    if (self.hasFired)
        return;
    
    self.hasFired = YES;

    [self hideKeyboard:YES];
    [self performSelector:@selector(cancelClickedAfterDelay) withObject:nil afterDelay:kKeyboardAnimationDuration];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Manage Done button state

- (void)doneClicked
{
    // Do nothing
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self doneClicked];
    return NO;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    self.done.enabled = NO;
    return YES;
}

- (BOOL)keyboardInputShouldDelete:(UITextField*)input
{
    self.done.enabled = input.text.length > 1;
    return YES;
}

- (BOOL)keyboardInput:(UITextView*)input shouldInsertText:(NSString *)newtext isMarkedText:(int)marked
{
    self.done.enabled = (self.text.text.length + newtext.length) > 0;
    return YES;
}

@end
